/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.taglib;

//import com.mr.qa.dao.impl.AnswerDAO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mr.qa.GlobalConfigs;

//import java.util.Enumeration;

public class QaPageUtilTag extends BodyTagSupport
{
    private static final Log log = LogFactory.getLog(QaPageUtilTag.class);
    
    private final static String PAGE_IDENTIFIER = "page";
    private final static String PAGESIZE_IDENTIFIER = "pageSize";
    private final static String RESULTSIZE_IDENTIFIER = "resultSize";
    
    private String action;
    
    public QaPageUtilTag()
    {
    }
    public int doStartTag() throws JspException
    {
        try
        {
            initPageLinkParameters();
            JspWriter out = pageContext.getOut();
            //out.println(makePageHtml());
            out.println("<div class=\"pb\"><table cellspacing=0 style=\"margin:0 auto;margin-top:7px;\" align=\"center\"><tr><td><div class='pagebox' id='_function_code_page'>"+makeNewPageLink()+"</div></td></tr></table></div>");
        }
        catch(Exception e)
        { 
            //log.error(e+" while Page Util Tag making pagination");
        }
        return this.EVAL_PAGE;
    }
    public int doEndTag() throws JspTagException 
    {
        return 0;
    }
    //the no of page the usr request;
    private int _curPageNo = 1;
    //the number of records in one page
    private int _pageSize = 1;
    //the total of records
    private int _resultSize = 1;
    
    private String _pageHtmlLinkQueryString = "";
    
    private String _url = "";
    
    HttpServletRequest request;
    
    private void initPageLinkParameters()
    {
        String errorLocation = "0";
        request = (HttpServletRequest)this.pageContext.getRequest();
        int pageNo = 1;
        String strPageNo = null;
        String strPageSizeInPara = null;
        String strPageSizeInRequ = null;
        Integer intPageSize = null;
        
        strPageNo = request.getParameter(PAGE_IDENTIFIER);
        strPageSizeInPara = request.getParameter(PAGESIZE_IDENTIFIER);
        String strResultSize = null;
        Integer intResultSize = null;
        try
        {
            _url = "";
            if(strPageSizeInPara == null)
            {
                strPageSizeInRequ = (String)request.getAttribute(PAGESIZE_IDENTIFIER);
                intPageSize = new Integer(strPageSizeInRequ);
            }
            else
            {
                intPageSize = new Integer(strPageSizeInPara);
            }
        }
        catch(ClassCastException cce)
        {
            intPageSize = (Integer)request.getAttribute(PAGESIZE_IDENTIFIER);
        }
        catch(Exception e)
        {
            if(action.indexOf("user.") > 0)
            {
                intPageSize = GlobalConfigs.SIZE_USER_LIST;
            }
            else
                intPageSize = 15;
        }
        try
        {
            strResultSize = (String)request.getAttribute(RESULTSIZE_IDENTIFIER);
            if(strResultSize != null)
            intResultSize = new Integer(strResultSize);
        }
        catch(ClassCastException cce)
        {
            intResultSize = (Integer)request.getAttribute(RESULTSIZE_IDENTIFIER);
        }
        catch(Exception e)
        { 
            log.warn(e+" while resultSize");
        }
        try
        {
            if(strPageNo != null)
            {
                errorLocation = "10";
                pageNo = new Integer(strPageNo).intValue();
                errorLocation = "11";
            }
            else
            {
                errorLocation = "20";
                strPageNo = (String)request.getAttribute(PAGE_IDENTIFIER);
                errorLocation = "21";
                if(strPageNo != null)
                pageNo = new Integer(strPageNo).intValue();
                errorLocation = "31";
            }
        }
        catch(ClassCastException cce)
        {
            errorLocation = "41";
            pageNo = (Integer)request.getAttribute(PAGE_IDENTIFIER);
            errorLocation = "42";
        }
        catch(Exception e)
        { 
            log.warn("errorLocation="+errorLocation+" ex="+e+" while pageNo, url="+getUrl(request));
        }
        _curPageNo = pageNo;
        _pageSize = intPageSize;
        _resultSize = intResultSize;
        _pageHtmlLinkQueryString = request.getContextPath()+action+"?"+makeParameters(request);
        //log.info("_curPageNo="+_curPageNo+",_pageSize="+_pageSize+",_resultSize="+_resultSize);
    }
    

    
    private String makeNewPageLink()
    {
        int[] pageNos = new int[2*10+2];
        if(_resultSize <= 0)return "";
        int numberOfPages = _resultSize/_pageSize+((_resultSize%_pageSize > 0)?1:0);
        //only one page,does not display pagination
        if(_curPageNo > numberOfPages)
            _curPageNo = numberOfPages;
        int i = 0;
        boolean showFirstNavi = false;
        boolean showEndNavi = false;
        if(numberOfPages == 1)
        {
            pageNos[1] = 1;
        }
        else if(numberOfPages <= 10)//&& numberOfPages > 1
        {
            pageNos[0] = _curPageNo-1;//pageNos[0] = 0;
            i = 1;
            while(i <= numberOfPages)
            {
                pageNos[i] = i;
                i = i+1;
            }
            if(_curPageNo < numberOfPages)
                pageNos[2*10+1] = _curPageNo+1;
        }
        else
        {
            //display previous page
            pageNos[0] = _curPageNo-1;
            //display first page
            //if(pageNos[0] > 0)showFirstNavi = true;
            //display next page
            if(_curPageNo < numberOfPages)
                pageNos[2*10+1] = _curPageNo+1;
            //if(pageNos[2*10+1] > 1)showEndNavi = true;
            
            /**
             * _curPageNo=31
             * numberOfPages=31
             * forwardNumberOfPages=31+10-1=40
             */
            int rightCount = 0;
            //16=18-2
            int diffToEnd = numberOfPages-_curPageNo; 
            if(diffToEnd >= (10-1))
            {
                i = 10+1;
            }
            else
            {
                i = 2*10-diffToEnd;//??-->test-->ok
            }
            int mid = i;
            pageNos[i] = _curPageNo;//11
            i = i+1;//12
            rightCount = 1;
            for(;i<=(2*10);i++)
            {
                pageNos[i] = pageNos[i-1]+1;
                if(pageNos[i] >= numberOfPages)break;//2008.7.3
                rightCount = rightCount+1;
            }
            //log.info("rightCount="+rightCount);
            //the lines of code were removed 
            /**
             * _curPageNo=1
             * no fill
             * _curPageNo=2
             * backNumberOfPages=2-8=-6
             */
            //log.info("rightCount="+rightCount);
            int leftCountTotal = 10-rightCount+10;
            //log.info("leftCountTotal="+leftCountTotal);
            int leftCount = 0;
            for(i=mid-1;(leftCount<=leftCountTotal && i >= 1);i--)//mid=_curPage
            {
                    pageNos[i] = pageNos[i+1]-1;//
                    leftCount = leftCount+1;
            }
        }
        if(numberOfPages > 3)
        {
            if(pageNos[0] > 0)showFirstNavi = true;
            if(pageNos[2*10+1] > 1)showEndNavi = true;
        }
        StringBuffer pageLinks = new StringBuffer();
        if(showFirstNavi)pageLinks.append(this.makeFirstPageHtmlLink());
        int pageNo = 0;
        pageNo = pageNos[0];
        if(pageNo != 0)
            pageLinks.append(this.makePreviousPageHtmlLink(pageNo));
        for(i=1;i<(2*10+1);i++)
        {
            pageNo = pageNos[i];
            if(pageNo > 0)
            {
                if(_curPageNo != pageNo)//?i
                {
                    pageLinks.append(this.makePageHtmlLink(pageNo));
                }
                else
                {
                    pageLinks.append(this.makeCurPageHtmlLink(pageNo));
                }
            }
            //log.info("["+i+"]="+pageNo);
        }
        pageNo = pageNos[2*10+1];
        if(pageNo != 0)
            pageLinks.append(this.makeNextPageHtmlLink(pageNo));
        if(showEndNavi)pageLinks.append(this.makeLastPageHtmlLink(numberOfPages));
        return pageLinks.toString();
    }

    private String makePageHtmlLink(int pageNo)
    {
        return "<span class='pagebox_num'><a href='"+_pageHtmlLinkQueryString+"&page="+pageNo+"&pageSize="+_pageSize+"'>"+pageNo+"</a></span>";
    }

    private String makeCurPageHtmlLink(int curPageNo)
    {
        return "<span class='pagebox_num_nonce'>"+curPageNo+"</span>";
    }


    private String makeFirstPageHtmlLink()
    {
        return "<span class='pagebox_num' title='First Page'><a href='"+_pageHtmlLinkQueryString+"&page="+1+"&pageSize="+_pageSize+"'>|<</a></span>";
    }

    private String makeLastPageHtmlLink(int lastPageNo)
    {
        return "<span class='pagebox_num' title='Last Page'><a href='"+_pageHtmlLinkQueryString+"&page="+lastPageNo+"&pageSize="+_pageSize+"'>>|</a></span>";
    }

    private String makePreviousPageHtmlLink(int previousPageNo)
    {
        return "<span class='pagebox_num' title='Previous Page'><a href='"+_pageHtmlLinkQueryString+"&page="+previousPageNo+"&pageSize="+_pageSize+"'><</a></span>";
    }

    private String makeNextPageHtmlLink(int nextPageNo)
    {
        return "<span class='pagebox_num' title='Next Page'><a href='"+_pageHtmlLinkQueryString+"&page="+nextPageNo+"&pageSize="+_pageSize+"'>></a></span>";
    }
    
    
    private String makePageHtml()
    {
        int page = 1;
        String strPage = null;
        String strPageSizeInPara = null;
        String strPageSizeInRequ = null;
        Integer intPageSize = null;
        
        strPage = request.getParameter(PAGE_IDENTIFIER);
        strPageSizeInPara = request.getParameter(PAGESIZE_IDENTIFIER);

        String strResultSize = null;
        Integer intResultSize = null;
        try
        {
            if(strPageSizeInPara == null)
            {
                strPageSizeInRequ = (String)request.getAttribute(PAGESIZE_IDENTIFIER);
                intPageSize = new Integer(strPageSizeInRequ);
            }
            else
            {
                intPageSize = new Integer(strPageSizeInPara);
            }
        }
        catch(Exception e)
        {
            if(action.indexOf("user.") > 0)
            {
                intPageSize = GlobalConfigs.SIZE_USER_LIST;
            }
            else
                intPageSize = 15;
        }
        try
        {
            strResultSize = (String)request.getAttribute(RESULTSIZE_IDENTIFIER);
            intResultSize = new Integer(strResultSize);
        }
        catch(Exception e)
        {
            intResultSize = (Integer)request.getAttribute(RESULTSIZE_IDENTIFIER);
        }
        try
        {
            if(strPage != null)
            {
                page = new Integer(strPage).intValue();
            }
            else
            {
                page = (Integer)request.getAttribute(PAGE_IDENTIFIER);
            }
        }
        catch(Exception e)
        {
            //log.error(e);
        }
        //System.out.println("action="+this.action);
        //System.out.println("page="+page);
        //System.out.println("pageSize="+intPageSize);
        //System.out.println("resultSize="+intResultSize);
        if(intResultSize > 0)
        {
            return makePageLinks(page,intPageSize,intResultSize,request);
        }
        return "";
    }
    private String makePageLinks(int page, int pageSize,int resultSize,HttpServletRequest request)
    {
        String href = request.getContextPath()+action+"?"+makeParameters(request);
        if(resultSize <= pageSize)return "";
        StringBuffer pageLinks = new StringBuffer();
        int totalPage = resultSize/pageSize+((resultSize%pageSize > 0)?1:0);
        //only one page,does not display pagination
        if(totalPage == 1)return "";
        if(page == 1)
        {
            pageLinks.append("<b>[1]</b>&nbsp;&nbsp;");
            for(int i=2;i<=totalPage;i++)
            {
                pageLinks.append("<a href='"+href+"&page="+i+"&pageSize="+pageSize+"'>["+i+"]</a>&nbsp;&nbsp;");
            }
        }
        else if(page > 1)
        {
            for(int i=1;i<page;i++)
            {
                pageLinks.append("<a href='"+href+"&page="+i+"&pageSize="+pageSize+"'>["+i+"]</a>&nbsp;&nbsp;");
            }
            pageLinks.append("<b>["+page+"]</b>&nbsp;&nbsp;");
            for(int i=page+1;i<=totalPage;i++)
            {
                pageLinks.append("<a href='"+href+"&page="+i+"&pageSize="+pageSize+"'>["+i+"]</a>&nbsp;&nbsp;");
            }
        }
        return pageLinks.toString();
    }
    
    private String getUrl(HttpServletRequest request)
    {
        java.util.Enumeration<String> paramters = request.getParameterNames();
        String parameterName = "";
        String parameterValue = "";
        String queryString = "";
        while(paramters.hasMoreElements())
        {
            parameterName = paramters.nextElement();
            parameterValue = request.getParameter(parameterName);
            if(queryString.length() > 0)
                queryString = queryString+"&"+parameterName+"="+parameterValue;
            else
                queryString = parameterName+"="+parameterValue;
        }
        return this.getAction()+"?"+queryString;
    }
    
    
    private String makeParameters(HttpServletRequest request)
    {
        java.util.Enumeration<String> paramters = request.getParameterNames();
        String parameterName = "";
        String parameterValue = "";
        String queryString = "";
        while(paramters.hasMoreElements())
        {
            parameterName = paramters.nextElement();
            if(!(PAGE_IDENTIFIER.equals(parameterName) || PAGESIZE_IDENTIFIER.equals(parameterName)))
            {
                parameterValue = request.getParameter(parameterName);
                //replace action value "view" with "get" when viewing a question to avoid viewcount increase
                if("/question.mrqa".equals(action) && "action".equals(parameterName) && "view".equals(parameterValue)) 
                {
                    parameterValue = "get";   
                }
                if(queryString.length() > 0)
                    queryString = queryString+"&"+parameterName+"="+parameterValue;
                else
                    queryString = parameterName+"="+parameterValue;
            }
        }
        return queryString;
    }

    public void setAction(String action)
    {
        this.action = action;
    }
    
    public String getAction()
    {
        return action;
    }
    
}
